package mark.tom.pistols.algorithm.generator;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.KeyGenerator;

/**
 * @Description: DES算法密钥生成器
 * @Author: ttmk110@163.com
 * @Package: mark.tom.pistols.algorithm.generator
 * @Date: 2020/5/3
 * @Copyright: 版权归 Mark 所有
 * <ModifyLog>
 * @ModifyContent:
 * @Author:
 * @Date: </ModifyLog>
 */
public final class DESKeyGenerator {

    private static final String KEY_ALGORITHM = "DES";

    public static String getKeyByDefault() throws NoSuchAlgorithmException {
        KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
        // 要生成多少位，只需要修改这里即可128, 192或256
        kg.init(56);
        return byteToHexString(kg.generateKey().getEncoded());
    }

    public static String getKeyByPassword(String password) throws NoSuchAlgorithmException {
        KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
        //要生成多少位，只需要修改这里即可128, 192或256
        // SecureRandom是生成安全随机数序列，password.getBytes()是种子，只要种子相同，序列就一样，所以生成的秘钥就一样。
        kg.init(56, new SecureRandom(password.getBytes()));
        return byteToHexString(kg.generateKey().getEncoded());
    }

    private static String byteToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte aByte : bytes) {
            String strHex = Integer.toHexString(aByte);
            if (strHex.length() > 3) {
                sb.append(strHex.substring(6));
            } else {
                if (strHex.length() < 2) {
                    sb.append("0").append(strHex);
                } else {
                    sb.append(strHex);
                }
            }
        }
        return sb.toString();
    }
}
